<template>
    <!-- 保持你原有的登录界面样式 -->
    <div style="text-align: center;margin: 0 20px">
        <div style="margin-top: 150px">
            <div style="font-size: 1.3rem ;text-shadow: 1px 0 1px black;;font-weight: bold">登录</div>
            <div style="font-size: 1rem;color: grey">在进入36k小说网之前请先输入用户名和密码进行登录</div>
        </div>

        <div style="margin-top: 50px ">
            <el-form :model="form" :rules="rules" ref="formRef">
                <!-- 用户名输入框 -->
                <el-form-item prop="username">
                    <el-input v-model="form.username" maxlength="20" type="text" placeholder="请输入用户名/邮箱" :disabled="loading">
                        <template #prefix>
                            <el-icon><User /></el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 密码输入框 -->
                <el-form-item prop="password">
                    <el-input v-model="form.password" type="password" maxlength="20" placeholder="请输入密码" style="margin-top:10px;" :disabled="loading" show-password>
                        <template #prefix>
                            <el-icon><Lock/></el-icon>
                        </template>
                    </el-input>
                </el-form-item>

                <!-- 记住我和忘记密码选项 -->
                <el-row>
                    <el-col :span="12" style="text-align: left">
                        <el-checkbox v-model="form.remember" label="记住我" :disabled="loading"></el-checkbox>
                    </el-col>
                    <el-col :span="12" style="text-align: right">
                        <el-link type="primary" style="translate: 0 -2px" @click="router.push('/reset')" :disabled="loading">忘记密码？</el-link>
                    </el-col>
                </el-row>
            </el-form>

            <!-- 登录按钮 -->
            <div style="margin-top: 40px">
                <el-button type="success" @click="userLogin" style="width: 80%" plain :loading="loading">立即登录</el-button>
            </div>

            <!-- 其他按钮保持不变 -->
            <el-divider><span style="font-size: 1rem;color: grey">没有账号？</span></el-divider>
            <div style="margin-top: 20px">
                <el-button @click="router.push('/register')" type="warning" style="width: 80%" plain :disabled="loading">立即注册</el-button>
            </div>

            <el-divider><span style="font-size: 1rem;color: grey">不登录了?</span></el-divider>
            <div style="margin-top: 20px">
                <el-button @click="router.push('/')" type="primary" style="width: 80%" plain :disabled="loading">回到主页</el-button>
            </div>
        </div>
    </div>
</template>

<script setup>
import router from "@/router";
import { User, Lock } from "@element-plus/icons-vue";
import { reactive, ref, onMounted } from "vue";
import { ElMessage } from "element-plus";
import request from "@/utils/request";
import { setAuthInfo } from '@/utils/authStorage';
// 表单引用
const formRef = ref()

// 表单数据
const form = reactive({
    username: '',
    password: '',
    remember: false // 记住我选项
})

// 加载状态
const loading = ref(false)

// 表单验证规则（与后端保持一致）
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' },
        { min: 3, max: 20, message: '用户名长度必须在3到20之间', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度必须在6到20之间', trigger: 'blur' }
    ]
}

/**
 * 登录处理函数
 */
async function userLogin() {
    // 表单验证
    formRef.value.validate(async (isValid) => {
        if (isValid) {
            try {
                loading.value = true;
                // 调用登录接口
                const response = await request.post('/api/auth/login', form);
                // 登录成功处理
                if (response.code === 200 && response.data) {
                    ElMessage.success('登录成功，欢迎回来！');
                    const { token, userId, role, username } = response.data;
                    // 根据"记住我"选项选择存储方式
                    const storage = form.remember ? localStorage : sessionStorage;
                    // 存储token和用户信息
                    setAuthInfo(
                        response.data.token,
                        { userId: response.data.userId, username: response.data.username, role: response.data.role },
                        form.remember
                    );
                    // 跳转到首页
                    router.push('/index');
                }else {
                    // 登录失败处理
                    ElMessage.error(response.message || '登录失败，请稍后重试');
                }
            } catch (error) {
                // 错误处理（后端抛出的异常会在这里被捕获）
                console.error('登录失败:', error);
                // 后端抛出的异常信息会在response拦截器中处理并显示
            } finally {
                loading.value = false;
            }
        }
    });
}

// 页面加载时初始化表单
onMounted(() => {
    // 从存储中获取记住的用户信息
    const userInfo = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo');
    if (userInfo) {
        try {
            const { username } = JSON.parse(userInfo);
            form.username = username;
            // 检查是否是localStorage存储（记住我）
            form.remember = !!localStorage.getItem('userInfo');
        } catch (e) {
            console.error('解析用户信息失败:', e);
        }
    }
});
</script>

<style scoped>
/* 保持原有样式 */
</style>
